package com.icode.readWriteLock;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: my_code
 * @Email: my_code@foxmail.com
 * @Create: 2020-12-12 16:05
 */
public class ReadWriteLockTest {

    public static void main(String[] args) {

        MyCache myCache = new MyCache();

        //写入
        for (int i = 0; i < 10; i++) {
            final int temp = i;
            new Thread(() -> {
                SimpleDateFormat bf = new SimpleDateFormat("HH-mm-ss");
                String format = bf.format(new Date());
                myCache.put(String.valueOf(temp), format);
            }, "W" + temp).start();
            //延时几秒
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //读取
        for (int i = 0; i < 10; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.get(String.valueOf(temp));
            },"R" + temp).start();
        }

    }
}

class MyCache {
    private volatile Map<String, Object> cache = new HashMap<String, Object>();
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void put(String key, Object value) {
        readWriteLock.writeLock().lock();
        try {

            System.out.println(Thread.currentThread().getName() + "写入" + value.toString());
            cache.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入成功");
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void get(String key) {
        readWriteLock.readLock().lock();
        try {
            //System.out.println(Thread.currentThread().getName() + "现在有"+readWriteLock.getReadLockCount()+"个线程持有读锁");
            System.out.println(Thread.currentThread().getName() + "读取" + key);
            Object value = cache.get(key);
            System.out.println(Thread.currentThread().getName() + "读取成功:"+value.toString());
        } finally {
            readWriteLock.readLock().unlock();
        }

    }
}